package com.gimi.cloud.jimi.common.mq.service.impl;


import com.gimi.cloud.jimi.common.mq.enume.QueueEnum;
import com.gimi.cloud.jimi.common.mq.service.MqCommonSenderService;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 基础消息发送者
 *
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2017-12-26
 **/
@Service
public class MqCommonSenderServiceImpl implements MqCommonSenderService {
    private RabbitMessagingTemplate rabbitMessagingTemplate;
    private RabbitAdmin rabbitAdmin;
    @Autowired
    public MqCommonSenderServiceImpl(RabbitMessagingTemplate rabbitMessagingTemplate, RabbitAdmin rabbitAdmin) {
        this.rabbitMessagingTemplate = rabbitMessagingTemplate;
        this.rabbitAdmin = rabbitAdmin;
    }

    @Override
    public void sendMessage2Rabbitmq(String exchangeName, String queueName, String routingKey, Object message) throws Exception {
        Queue queue = new Queue(queueName);
        rabbitAdmin.declareQueue(queue); //定义queue
        TopicExchange topicExchange = new TopicExchange(exchangeName);
        rabbitAdmin.declareExchange(topicExchange);//定义exchange
        Binding binding = BindingBuilder.bind(queue).to(topicExchange).with(routingKey);
        rabbitAdmin.declareBinding(binding); //绑定队列
        this.rabbitMessagingTemplate.convertAndSend(exchangeName,routingKey,message);
    }

    @Override
    public void sendMessage2Rabbitmq(QueueEnum queueEnum, Object message) throws Exception {
        this.sendMessage2Rabbitmq(queueEnum.getExchange(),queueEnum.getQueueName(),queueEnum.getRoutingKey(),message);
    }
}
